package com.bc.bcapi.service;

import com.bc.bcapi.dao.*;
import com.bc.bccore.redis.RedisService;
import com.bc.bcmodel.consts.RedissCacheKey;
import com.bc.bcmodel.domain.*;
import com.bc.bcmodel.req.ProjectGetByIdReq;
import com.bc.bcmodel.resp.ProjectDetailResp;
import com.bc.bcmodel.resp.ProjectGetByIdResp;
import com.bc.bcmodel.resp.ProjectRaiseResp;
import com.bc.bcmodel.resp.UserBuyerLikeFavoriteResp;
import com.bc.commoncore.util.DateUtil;
import com.bc.commoncore.util.ParseHelper;
import com.bc.commoncore.util.StringUtils;
import com.bc.commonentity.common.JsonResult;
import com.fasterxml.jackson.databind.node.BigIntegerNode;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mchange.v2.cfg.PropertiesConfigSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.DateTimeException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.math.BigInteger;

/**
 * @Name T_Project_searchService * @Description * @Author generation * @Date 2018/8/12 20:44:10 * @Version 1.0
 **/
@Service
public class T_Project_searchService {
    @Resource
    T_ProjectMapper t_projectMapper;
    @Resource
    T_Project_searchMapper t_Project_searchMapper;
    @Resource
    T_Project_analysisMapper t_project_analysisMapper;
    @Resource
    T_Project_contactMapper t_project_contactMapper;
    @Resource
    RedisService redisService;
    @Resource
    T_User_favoriteMapper t_user_favoriteMapper;
    @Resource
    T_Project_tagMapper t_project_tagMapper;//查询打标数
    @Resource
    T_Project_tag_relationMapper t_project_tag_relationMapper;//查询参标数
    @Resource
    T_OrderMapper t_orderMapper;
    @Resource
    T_User_seller_bonusMapper t_user_seller_bonusMapper;
    @Resource
    T_User_browseMapper t_user_browseMapper;
    @Resource
    T_ProjectService t_projectService;

    /**
     * 保存单条数据     *      * @return
     */

    public int insert(T_Project_searchModel req) {
        return t_Project_searchMapper.insert(req);
    }

    /**
     * 批量增加数据     *      * @return
     */

    public int insertBatch(List<T_Project_searchModel> req) {
        return t_Project_searchMapper.insertBatch(req);
    }

    /**
     * 根据对象属性查找满足条件的第一条数据     *      * @return
     */

    public T_Project_searchModel findByNamedParam(T_Project_searchModel req) {
        return t_Project_searchMapper.findByNamedParam(req);
    }

    /**
     * 根据对象查询所有数据     *      * @return
     */

    public List<T_Project_searchModel> getAllList(T_Project_searchModel req) {
        return t_Project_searchMapper.findByNamedParamList(req);
    }

    /**
     * 根据对象查询所有分页数据     *      * @return
     */

    public PageInfo<T_Project_searchModel> getList(T_Project_searchModel req) {
        PageHelper.startPage(req.getPage_index(), req.getPage_size());
        List<T_Project_searchModel> list = t_Project_searchMapper.findByNamedParamList(req);
        return new PageInfo<T_Project_searchModel>(list);
    }

    /**
     * 更新指定对象     *      * @return
     */

    public int update(T_Project_searchModel req) {
        return t_Project_searchMapper.update(req);
    }

    /**
     * 删除指定数据     *      * @return
     */

    public int delete(BigInteger id) {
        return t_Project_searchMapper.delete(id);
    }

    /**
     * 根据条件统计数据量     *      * @return
     */

    public long count(T_Project_searchModel req) {
        return t_Project_searchMapper.count(req);
    }

    /**
     * 创建搜索列表条件返回值属性方法
     */
    public JsonResult createSearch() {
        JsonResult js = new JsonResult();
        /**查询所有需要操作的项目ID*/
        List<String> listIds = t_projectMapper.getPids();
        for (String pid : listIds) {
            T_ProjectModel t_projectModel = new T_ProjectModel();
            T_Project_searchModel searchModel = new T_Project_searchModel();
            searchModel.setPid(pid);
            t_projectModel.setPid(pid);
            //获取到列表
            T_ProjectModel resultProjectModel = t_projectMapper.findByNamedParam(t_projectModel);
            /*
             * is_bonus 是否有bonus开始;
             * **/
            T_User_seller_bonusModel t_user_seller_bonusModel = new T_User_seller_bonusModel();
            t_user_seller_bonusModel.setUser_id(resultProjectModel.getUser_id());
            List<T_User_seller_bonusModel> listBonus = t_user_seller_bonusMapper.findByNamedParamList(t_user_seller_bonusModel);
            long listBonusCount = listBonus.stream().filter(t -> t.getBonus_value().compareTo(BigDecimal.ZERO) > 0).count();
            int issetBonus = 0;
            if (listBonusCount > 0) {
                issetBonus = 1;
            }
            searchModel.setIs_bonus(issetBonus);
            /*
             * is_bonus 是否有bonus结束;
             * **/
//            是否有专家点评;
            int expert_comment_count = 0;
            T_Project_analysisModel t_project_analysisModel = new T_Project_analysisModel();
            t_project_analysisModel.setPid(pid);
            int analysisCounter = t_project_analysisMapper.count(t_project_analysisModel);

            if (analysisCounter > 0) {
                expert_comment_count = 1;
            }
            searchModel.setBusiness_analysis_count(expert_comment_count);
//            is_video 是否有视频分析;
            searchModel.setIs_video(resultProjectModel.getVideourl().equals("") ? 0 : 1);
//            is_user 是否有用户量;
            searchModel.setIs_user(resultProjectModel.getUser_count().equals("") ? 0 : 1);
//            is_flowing_water 是否有流水;
            searchModel.setIs_flowing_water(resultProjectModel.getFlowing_water_count().equals("") ? 0 : 1);
//            is_real_industry 是否有实体产业;
            searchModel.setIs_real_industry(resultProjectModel.getImg_scene().equals("") ? 0 : 1);
//            is_code_public 是否代码公开;
            T_Project_contactModel projectContactModel = new T_Project_contactModel();
            projectContactModel.setPid(pid);
            projectContactModel.setContact_name("github");
            searchModel.setIs_code_public(t_project_contactMapper.count(projectContactModel) <= 0 ? 0 : 1);

            //查询完成率
            ProjectRaiseResp projectRaiseResp = getProjectRaise(pid);
//            is_transaction 是否实时交易;
            int is_transaction = t_projectService.SetIs_transaction(pid);
            searchModel.setIs_transaction(is_transaction);
            //总募集
            searchModel.setTotal_amount(projectRaiseResp.getTotal_amount());
            //已募集
            searchModel.setExists_amount(projectRaiseResp.getExists_amount());
            //完成率
            searchModel.setFinish_rate(projectRaiseResp.getFinish_rate());

//            pstatus ICO状态，默认1进行中，2即将开始，3已结束;
            //进行中，时间范围正常
            //即将开始，开始时间未达到
            //已结束，时间超出范围
            int pstatus = 0;//未知状态
            Date start_time = resultProjectModel.getStart_time();
            Date end_time = resultProjectModel.getEnd_time();
            Date current_time = DateUtil.getToday();

            if (current_time.getTime() > end_time.getTime()) {
                //已结束
                pstatus = 3;
            } else if (current_time.getTime() > start_time.getTime() && current_time.getTime() < end_time.getTime()) {
                //进行中
                pstatus = 1;
            } else if (start_time.getTime() < current_time.getTime()) {
                //即将开始
                pstatus = 2;
            }
            searchModel.setPstatus(pstatus);
//            view_count 浏览次数;
            T_User_browseModel t_user_browseModel = new T_User_browseModel();
            t_project_analysisModel.setPid(resultProjectModel.getPid());
            int browseCount = t_user_browseMapper.count(t_user_browseModel);
            searchModel.setView_count(browseCount);
//            favorite_count 收藏数;
//            like_count 喜欢数;
            UserBuyerLikeFavoriteResp userBuyerLikeFavoriteResp =
                    t_user_favoriteMapper.getLikeFavoriteCount(pid);
            int like_count = userBuyerLikeFavoriteResp == null ? 0 : userBuyerLikeFavoriteResp.getLike_count();
            int favorite_count = userBuyerLikeFavoriteResp == null ? 0 : userBuyerLikeFavoriteResp.getFavorite_count();
            searchModel.setLike_count(like_count);
            searchModel.setFavorite_count(favorite_count);
//            tag_count 打标数;
            T_Project_tagModel t_project_tagModel = new T_Project_tagModel();
            t_project_tagModel.setPid(pid);
            searchModel.setTag_count(t_project_tagMapper.count(t_project_tagModel));
//            join_count 参标数;
            T_Project_tag_relationModel t_project_tag_relationModel = new T_Project_tag_relationModel();
            t_project_tag_relationModel.setPid(pid);
            int join_count = t_project_tag_relationMapper.count(t_project_tag_relationModel);
            searchModel.setJoin_count(searchModel.getTag_count() + join_count);
//            distribution_count 分销数;
            //有多少比订单是走的bonus
            searchModel.setDistribution_count(t_orderMapper.getDistributionCount(pid));
//            professional_analysis_count 专业分析数;
            int professional_analysis_count = t_Project_searchMapper.analysisAllCountByPid(pid);
            searchModel.setProfessional_analysis_count(professional_analysis_count);
//            tag_block 打标信息格式:标签内容,数量|标签内容,数量|;
            List<T_Project_tagModel> listTagModel = t_Project_searchMapper.getTag_blockByPid(pid);
            String tag_block = "";
            for (T_Project_tagModel item : listTagModel) {
                tag_block += item.getTag_name() + "," + item.getCounter() + "|";
            }
            searchModel.setTag_block(tag_block);
//            recommend_comment 推荐评论;
            String recommend_comment = t_Project_searchMapper.getRecommend_comment(pid);
            searchModel.setRecommend_comment(recommend_comment);
            upsert(searchModel);
        }
        return js;
    }

    public void upsert(T_Project_searchModel searchModel) {
        T_Project_searchModel t_project_searchModel = new T_Project_searchModel();
        t_project_searchModel.setPid(searchModel.getPid());
        if (!searchModel.getPid().equals("") && t_Project_searchMapper.count(t_project_searchModel) > 0) {
            //修改
            t_Project_searchMapper.update(searchModel);
        } else {
            //添加
            t_Project_searchMapper.insert(searchModel);
        }
    }

    /**
     * 计算完成率
     */
    private ProjectRaiseResp getProjectRaise(String pid) {
        ProjectRaiseResp resp = new ProjectRaiseResp();
        //剩余募集金额
        BigDecimal spare_amount = t_Project_searchMapper.getProjectBalanceByPid(pid);
        spare_amount = spare_amount == null ? new BigDecimal(0) : spare_amount;
        BigDecimal exists_amount = t_orderMapper.getExistsFinal_sell_count(pid);
        exists_amount = exists_amount == null ? new BigDecimal(0) : exists_amount;
        //总募集金额
        BigDecimal total_amount = spare_amount.add(exists_amount);

        BigDecimal rate_total_amount = total_amount.compareTo(BigDecimal.ZERO) == 0 ? new BigDecimal(1) : total_amount;

//        finish_rate 完成比例; 完成数/总数*100
//        exists_amount.doubleValue().
        Double finish_rate = exists_amount.doubleValue() /
                rate_total_amount.doubleValue() * 100;
        resp.setExists_amount(exists_amount);
        resp.setSpare_amount(spare_amount);
        resp.setTotal_amount(total_amount);
        resp.setFinish_rate(new BigDecimal(finish_rate).setScale(2, BigDecimal.ROUND_UP));
        return resp;
    }

    public JsonResult projectSellRecord(String uid) {
        ProjectGetByIdResp projectGetByIdResp = t_projectMapper.getPidByUserId(uid);
        HashMap<String, Object> rst = new HashMap<>();
        rst.put("token", "");
        rst.put("remain", 0);
        rst.put("selled", 0);
        rst.put("rate", 0);

        if (projectGetByIdResp == null) {
            return new JsonResult(rst);
        }
        String pid = projectGetByIdResp.getPid();
        ProjectDetailResp projectDetailResp = t_projectMapper.getDetailByPid(pid);
        ProjectRaiseResp projectRaiseResp = getProjectRaise(pid);
        rst.put("token", projectDetailResp == null ? "" : projectDetailResp.getIco_name());
        rst.put("remain", projectRaiseResp.getExists_amount());
        rst.put("selled", projectRaiseResp.getSpare_amount());
        rst.put("rate", projectRaiseResp.getFinish_rate());
        return new JsonResult(rst);
    }

}